﻿using DevExpress.XtraEditors;
using MesProjectWinform.BasicData.Entity;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.BasicData.基础实现.wuliao
{
    public partial class wuliao : DevExpress.XtraEditors.XtraForm
    {
        private int pageindex = 1;
        private int pagesize = 2;  // 默认每页显示2条数据
        private int totalCount = 0;
        private int totalPages = 0;
        private readonly string apiBaseUrl = "http://localhost:5052";

        public wuliao()
        {
            InitializeComponent();
            InitPageSizeCombo();
            InitMaterialTypeCombo();
            InitCheckBoxEvent();
            
            // 添加窗体加载事件处理
            this.Load += Wuliao_Load;
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void Wuliao_Load(object sender, EventArgs e)
        {
            // 窗体加载时执行查询，确保数据立即显示
            LoadData();
        }

        private void InitCheckBoxEvent()
        {
            checkBox1.CheckedChanged += checkBox1_CheckedChanged;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            // 全选/取消全选的逻辑
            bool isChecked = checkBox1.Checked;
            
            gridView1.BeginUpdate();
            try
            {
                // 如果想要全选
                if (isChecked)
                {
                    gridView1.SelectAll();
                }
                // 如果想要取消全选
                else
                {
                    gridView1.ClearSelection();
                }
            }
            finally
            {
                gridView1.EndUpdate();
            }
        }

        private void InitPageSizeCombo()
        {
            cmbPageSize.Items.AddRange(new object[] { 2, 5, 10, 20, 50 });
            cmbPageSize.SelectedItem = pagesize;
        }

        private void InitMaterialTypeCombo()
        {
            comboBox1.Items.Add("");
            comboBox1.Items.Add("原材料");
            comboBox1.Items.Add("半成品");
            comboBox1.Items.Add("成品");
            comboBox1.Items.Add("工具");
            comboBox1.Items.Add("其他");
            comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 构建请求URL，使用接口要求的参数名
                string url = $"/api/Materialgroup/GetMaterialgroup?pageindex={pageindex}&pagesize={pagesize}";
                
                // 添加物料编码查询条件
                if (!string.IsNullOrWhiteSpace(textEdit1.Text))
                    url += $"&Materialgroupcode={textEdit1.Text.Trim()}";
                
                // 添加物料名称查询条件
                if (!string.IsNullOrWhiteSpace(textEdit2.Text))
                    url += $"&Materialgroupname={textEdit2.Text.Trim()}";
                
                // 添加物料类型查询条件
                if (comboBox1.SelectedIndex > 0)
                    url += $"&Materialgrouptype={comboBox1.SelectedItem}";
                
                // 临时保存原始BaseUrl
                string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                try
                {
                    // 临时修改BaseUrl为端口5052
                    Properties.Settings.Default.BaseUrl = "http://localhost:5052/";
                    
                    // 使用HttpClientHelper发送请求
                    string result = await HttpClientHelper.RequestUrl(RequestType.Get, url, "");
                    
                    if (!string.IsNullOrEmpty(result))
                    {
                        MaterialgroupDto materialData = JsonConvert.DeserializeObject<MaterialgroupDto>(result);
                        
                        if (materialData?.Data != null)
                        {
                            // 确保数据中的工艺路线字段正确显示
                            foreach (var item in materialData.Data)
                            {
                                // 如果物料类型不是成品或半成品，或者工艺路线为空，则设置为"-"
                                if ((item.Materialgrouptype != "成品" && item.Materialgrouptype != "半成品") ||
                                    string.IsNullOrWhiteSpace(item.Operationalpathid))
                                {
                                    item.Operationalpathid = "-";
                                }
                            }

                            // 检查数据中的ID是否有效
                            bool hasInvalidId = false;
                            foreach (var item in materialData.Data)
                            {
                                if (item.Id <= 0)
                                {
                                    hasInvalidId = true;
                                    break;
                                }
                            }
                            
                            if (hasInvalidId)
                            {
                                // 移除警告，静默处理无效ID
                                Console.WriteLine("警告：数据源中包含无效的ID值");
                            }

                            gridControl1.DataSource = materialData.Data;
                            totalCount = materialData.TotalCount;
                            totalPages = (int)Math.Ceiling((double)totalCount / pagesize);
                            UpdatePageInfo();
                        }
                        else
                        {
                            gridControl1.DataSource = null;
                            totalCount = 0;
                            totalPages = 0;
                            UpdatePageInfo();
                        }
                    }
                    else
                    {
                        // 静默处理数据获取失败的情况，显示空数据
                        gridControl1.DataSource = null;
                        totalCount = 0;
                        totalPages = 0;
                        UpdatePageInfo();
                    }
                }
                finally
                {
                    // 恢复原始BaseUrl
                    Properties.Settings.Default.BaseUrl = originalBaseUrl;
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不显示错误弹窗
                Console.WriteLine($"查询数据出错：{ex.Message}");
                
                // 显示空数据
                gridControl1.DataSource = null;
                totalCount = 0;
                totalPages = 0;
                UpdatePageInfo();
            }
        }

        /// <summary>
        /// 更新分页信息
        /// </summary>
        private void UpdatePageInfo()
        {
            lblPageInfo.Text = $"第 {pageindex} 页/共 {totalPages} 页，总记录数：{totalCount}";
            btnPrevPage.Enabled = pageindex > 1;
            btnNextPage.Enabled = pageindex < totalPages;
        }

        /// <summary>
        /// 上一页
        /// </summary>
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (pageindex > 1)
            {
                pageindex--;
                LoadData();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (pageindex < totalPages)
            {
                pageindex++;
                LoadData();
            }
        }

        /// <summary>
        /// 选择每页显示数量
        /// </summary>
        private void cmbPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPageSize.SelectedItem != null)
            {
                pagesize = Convert.ToInt32(cmbPageSize.SelectedItem);
                pageindex = 1; // 重置为第一页
                LoadData();
            }
        }

        /// <summary>
        /// 修改按钮点击处理（表格中的修改按钮）
        /// </summary>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前点击的行的数据
            var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.FocusedRowHandle >= 0)
            {
                var focusedRow = view.GetRow(view.FocusedRowHandle) as Materialgroupmodel;
                if (focusedRow != null)
                {
                    try
                    {
                        // 直接打开修改窗口，传递ID，让wuup窗体自己获取数据并反填
                        var editForm = new wuup(focusedRow.Id);
                        if (editForm.ShowDialog() == DialogResult.OK)
                        {
                            // 如果修改成功，刷新数据
                            LoadData();
                        }
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show($"操作失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                XtraMessageBox.Show("请先选择要修改的物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        private async void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前选中行的数据
            var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.FocusedRowHandle >= 0)
            {
                // 获取当前行的ID
                var row = view.GetRow(view.FocusedRowHandle) as Materialgroupmodel;
                if (row != null && row.Id > 0)
                {
                    // 显示确认对话框
                    DialogResult result = XtraMessageBox.Show("是否确认删除此条物料信息？", "确认删除", 
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    
                    if (result == DialogResult.Yes)
                    {
                        try
                        {
                            string url = $"/api/Materialgroup/DeleteMaterialgroup?id={row.Id}";
                            
                            // 临时保存原始BaseUrl
                            string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                            try
                            {
                                // 临时修改BaseUrl为端口5052
                                Properties.Settings.Default.BaseUrl = "http://localhost:5052/";
                                
                                // 使用 HttpClientHelper 发送请求
                                string responseResult = await HttpClientHelper.RequestUrl(RequestType.Put, url, "");
                                
                                if (!string.IsNullOrEmpty(responseResult))
                                {
                                    XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    // 刷新数据
                                    LoadData();
                                }
                                else
                                {
                                    XtraMessageBox.Show("删除失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                            finally
                            {
                                // 恢复原始BaseUrl
                                Properties.Settings.Default.BaseUrl = originalBaseUrl;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"删除出错：{ex.Message}");
                            XtraMessageBox.Show("删除失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            else
            {
                XtraMessageBox.Show("请先选择要删除的物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            pageindex = 1; // 查询时重置为第一页
            LoadData();
        }

        /// <summary>
        /// 新增/修改按钮点击处理（页面顶部的"新增"按钮）
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            // 获取选中的行
            int[] selectedRows = gridView1.GetSelectedRows();
            
            // 如果有选中行，则打开修改窗口并传递选中行的数据
            if (selectedRows.Length > 0)
            {
                if (selectedRows.Length > 1)
                {
                    XtraMessageBox.Show("只能选择一条记录进行修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中行的物料ID
                var selectedRow = gridView1.GetRow(selectedRows[0]) as Materialgroupmodel;
                if (selectedRow != null)
                {
                    try
                    {
                        // 直接打开修改窗口，传递ID，让wuup窗体自己获取数据并反填
                        var editForm = new wuup(selectedRow.Id);
                        if (editForm.ShowDialog() == DialogResult.OK)
                        {
                            // 如果修改成功，刷新数据
                            LoadData();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"操作失败：{ex.Message}");
                        XtraMessageBox.Show($"操作失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                // 如果没有选中行，则打开新增窗口
                var addForm = new wuup();
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果添加成功，刷新数据
                    LoadData();
                }
            }
        }
    }
}